﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using SienSchoofsProject.Models;
using System.Net.Mail;
using System.Net;

namespace SienSchoofsProject.Controllers
{
    [Authorize]
    public class AccountController : BaseController
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", Resources.Resources.LoginIncorrect);
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { emailadres = model.emailadres }, false);
                    //De nieuwe user de 'standaard' rol toewijzen
                    var roles = (SimpleRoleProvider)Roles.Provider;
                    roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Standaard" });
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? Resources.Resources.PwChange
                : message == ManageMessageId.SetPasswordSuccess ? Resources.Resources.PwSet
                : message == ManageMessageId.RemoveLoginSuccess ? Resources.Resources.LoginIncorrect
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", Resources.Resources.PwConfirmWrong);
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", String.Format(Resources.Resources.UnableLocalAcc, User.Identity.Name));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { emailadres = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new FilmDb())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", Resources.Resources.UsernameExists);
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        //
        // GET: /Account/ForgotPassword

        [AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        //
        // POST: /Account/ForgotPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(string UserName)
        {
            //Kijk of de user besstaat
            var user = Membership.GetUser(UserName);
            if (user == null)
            {
                TempData["Message"] = Resources.Resources.UserNotExist;
            }
            else
            {
                //genereer een password reset token
                var token = WebSecurity.GeneratePasswordResetToken(UserName);
                //creëer een url met de reset token
                var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { username = UserName, resetToken = token }, "http") + Resources.Resources.ForgotPWResetLink;
                //haal de email op van deze user
                FilmDb db = new FilmDb();
                var emailid = (from i in db.UserProfiles
                               where i.UserName == UserName
                               select i.emailadres).FirstOrDefault();
                //verzend mail
                string subject = Resources.Resources.ForgotPWSub;
                string body = Resources.Resources.ForgotPWBody + resetLink;
                try
                {
                    SendEMail(emailid, subject, body);
                    TempData["Message"] = Resources.Resources.ForgotPWSent;
                }
                catch (Exception ex)
                {
                    TempData["Message"] = Resources.Resources.ForgotPWError + ex.Message;
                }
            }

            return View();
        }

        [AllowAnonymous]
        public ActionResult ResetPassword(string username, string resetToken)
        {
            FilmDb db = new FilmDb();
            //TODO: Kijk of de username en resetToken overeenkomen met elkaar, en voer vervolgens de volgende code uit
            //haal de userid op van de verkregen username
            var userid = (from i in db.UserProfiles
                          where i.UserName == username
                          select i.UserId).FirstOrDefault();
            //controleer of de userid en token overeenkomen
            bool any = (from j in db.webpages_Memberships
                        where (j.UserId == userid)
                        && (j.PasswordVerificationToken == resetToken)
                        select j).Any();

            //als de token klopt
            if (any == true)
            {
                //genereer een random wachtwoord
                string newpassword = GenerateRandomPassword(6);
                //reset het wachtwoord
                bool response = WebSecurity.ResetPassword(resetToken, newpassword);
                if (response == true)
                {
                    //clear de PasswordVerificationToken van de Membership table. 
                    //Dit voorkomt ongewenste resets, zoals wanneer iemands e-mailadres gehacked zou worden en de reset mail onderschept zou worden.
                    WebSecurity.ResetPassword(resetToken, newpassword);
                    //haal de email op van de gebruiker voor het versturen van het nieuwe wachtwoord
                    var emailid = (from i in db.UserProfiles
                                   where i.UserName == username
                                   select i.emailadres).FirstOrDefault();
                    //verzend email
                    string subject = Resources.Resources.ResetPwSub;
                    string body = Resources.Resources.ResetPwBody + newpassword;
                    try
                    {
                        SendEMail(emailid, subject, body);
                        TempData["Message"] = Resources.Resources.ForgotPWSent;
                    }
                    catch (Exception ex)
                    {
                        //fout bij het versturen van het wachtwoord
                        TempData["Title"] = Resources.Resources.Error;
                        TempData["Message"] = Resources.Resources.ForgotPWError;
                    }

                    //weergeef een bevestigingsbericht
                    TempData["Title"] = Resources.Resources.ResetPwSentTitle;
                    TempData["Message"] = Resources.Resources.ResetPwSentMsg;
                }
                    //fout bij het versturen & reset van het wachtwoord
                else
                {
                    TempData["Title"] = Resources.Resources.ResetPwSentErrorTitle;
                    TempData["Message"] = Resources.Resources.ResetPwSentErrorMsg;
                }
            }
            //als de token niet klopt
            else
            {
                TempData["Title"] = Resources.Resources.Error;
                TempData["Message"] = Resources.Resources.TokenError;
            }

            return View();
        }

        //genereer een random wacwhtword van een bepaalde lengte, bestaande uit alfanumerieke tekens
        private string GenerateRandomPassword(int length)
        {
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-*&#+";
            char[] chars = new char[length];
            Random rd = new Random();
            for (int i = 0; i < length; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }
            return new string(chars);
        }

        //verstuur een mail
        private void SendEMail(string emailid, string subject, string body)
        {
            //van welk emailadres (en naam) en het gmail wachtwoord
            var van = new MailAddress("Sienstestemail@gmail.com", "FilmDb");           
            const string wachtwoord = "Sientest";

            //gmail smtp instellingen
            SmtpClient client = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(van.Address, wachtwoord)
            };

            //een bericht opstellen
            MailMessage msg = new MailMessage();
            msg.From = van; //van wie de mail verstuurd wordt (Sientestemail)
            msg.To.Add(new MailAddress(emailid)); //naar wie  de mail verstuurd wordt

            msg.Subject = subject; //email onderwerp
            msg.IsBodyHtml = true; //email heeft html opmaak
            msg.Body = body; //de body van de mail

            client.Send(msg); //verzend mail
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return Resources.Resources.DuplicateUserName;

                case MembershipCreateStatus.DuplicateEmail:
                    return Resources.Resources.DuplicateEmail;

                case MembershipCreateStatus.InvalidPassword:
                    return Resources.Resources.InvalidPassword;

                case MembershipCreateStatus.InvalidEmail:
                    return Resources.Resources.InvalidEmail;

                case MembershipCreateStatus.InvalidAnswer:
                    return Resources.Resources.InvalidAnswer;

                case MembershipCreateStatus.InvalidQuestion:
                    return Resources.Resources.InvalidQuestion;

                case MembershipCreateStatus.InvalidUserName:
                    return Resources.Resources.InvalidUserName;

                case MembershipCreateStatus.ProviderError:
                    return Resources.Resources.ProviderError;

                case MembershipCreateStatus.UserRejected:
                    return Resources.Resources.UserRejected;

                default:
                    return Resources.Resources.DefaultError;
            }
        }
        #endregion
    }
}
